//
//  HEServerOrgViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2021/5/25.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEServerOrgViewController.h"
#import "HEServerOrgCell.h"
#import "HEServerOrgModel.h"
#import "HEFindDoctorViewController.h"
#import "HEFindTeamViewController.h"

@interface HEServerOrgViewController ()<UITableViewDelegate, UITableViewDataSource, BMKLocationManagerDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray <HEServerOrgModel *> * dataSourceArr;
@property (nonatomic, strong) BMKLocationManager *locationManager; //定位对象

@end

@implementation HEServerOrgViewController

- (NSMutableArray<HEServerOrgModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"机构列表";
    [self initUI];
    [self getCurrentLocal];
    [self setCustomTableView:_tableView];
}

- (void)initUI {
    
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollsToTop = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.backgroundColor = CViewBgColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    __weak __typeof(&*self)weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        weakSelf.isFromHeadRefresh = YES;
        [weakSelf loadData];
    }];
 
 
    [_tableView registerClass:[HEServerOrgCell class] forCellReuseIdentifier: KHEServerOrgCell];
}

- (void)loadData {
    
    NSMutableDictionary *params = @{}.mutableCopy;
    [params setValue:[NSNumber numberWithInteger:_type] forKey:@"server_type"];
    [params setValue: [NSString stringWithFormat:@"%f", [UserManager sharedUserManager].currentCoordinate.longitude] forKey:@"longitude"];
    [params setValue: [NSString stringWithFormat:@"%f", [UserManager sharedUserManager].currentCoordinate.latitude] forKey:@"latitude"];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:Khospital parameters:params success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        
        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
        }
        
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [self.dataSourceArr addObjectsFromArray:[HEServerOrgModel mj_objectArrayWithKeyValuesArray:response.data]];
        [self.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
 
        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }

    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
     }];
}

#pragma mark - 单次定位
- (void)getCurrentLocal {
    [self.locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        
        if (location.location) {
            [UserManager sharedUserManager].currentCoordinate = location.location.coordinate;
            [self loadData];
        }else {
            [self loadData];
        }
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEServerOrgCell *cell = [tableView dequeueReusableCellWithIdentifier: KHEServerOrgCell];
    [cell configCellWithModel:self.dataSourceArr[indexPath.row] indexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: KHEServerOrgCell cacheByIndexPath:indexPath configuration:^(HEServerOrgCell *cell) {
        [cell configCellWithModel:self.dataSourceArr[indexPath.row] indexPath:indexPath];
    }];
}
 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEServerOrgModel *model = _dataSourceArr[indexPath.row];
    if (_type == HEServerOrgTypeDoctor) {
        HEFindDoctorViewController *vc = [HEFindDoctorViewController new];
        vc.selectOrgModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        HEFindTeamViewController *vc = [HEFindTeamViewController new];
        vc.selectOrgModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
 
- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        //初始化BMKLocationManager类的实例
        _locationManager = [[BMKLocationManager alloc] init];
        //设置定位管理类实例的代理
        _locationManager.delegate = self;
        //设定定位坐标系类型，默认为 BMKLocationCoordinateTypeGCJ02
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设定定位精度，默认为 kCLLocationAccuracyBest
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设定定位类型，默认为 CLActivityTypeAutomotiveNavigation
        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //指定定位是否会被系统自动暂停，默认为NO
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        /**
         是否允许后台定位，默认为NO。只在iOS 9.0及之后起作用。
         设置为YES的时候必须保证 Background Modes 中的 Location updates 处于选中状态，否则会抛出异常。
         由于iOS系统限制，需要在定位未开始之前或定位停止之后，修改该属性的值才会有效果。
         */
        _locationManager.allowsBackgroundLocationUpdates = NO;
        /**
         指定单次定位超时时间,默认为10s，最小值是2s。注意单次定位请求前设置。
         注意: 单次定位超时时间从确定了定位权限(非kCLAuthorizationStatusNotDetermined状态)
         后开始计算。
         */
        _locationManager.locationTimeout = 10;
    }
    return _locationManager;
}

@end
